package models

import (
	"context"
	"github.com/go-redis/redis"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)
var Db *DB

func init() {
	Db = getDb()
}

type DB struct {
	MongoDb    *mongo.Client
	RedisDb    *redis.Client
	Ctx        context.Context
	CancelFunc context.CancelFunc
}

func (d *DB) mongoInit() error {
	var (
		clientOptions *options.ClientOptions
		client        *mongo.Client
		ctx           context.Context
		cancel        context.CancelFunc
		err           error
	)
	// 设置客户端连接配置
	clientOptions = options.Client().ApplyURI("mongodb://localhost:27017")
	// 连接到MongoDB
	ctx, cancel = context.WithCancel(context.Background())
	if client, err = mongo.Connect(ctx, clientOptions); err != nil {
		log.Println("Mongo连接失败")
		cancel()
		return err
	}
	// 检查连接
	if err = client.Ping(context.TODO(), nil); err != nil {
		log.Println("Mongo检查失败")
		return err
	}
	log.Println("连接MongoDb成功")
	d.MongoDb = client
	d.CancelFunc = cancel
	d.Ctx = ctx
	return nil
}
func (d *DB) redisInit() error {
	var (
		client *redis.Client
		err    error
	)
	client = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	if _, err = client.Ping().Result(); err != nil {
		log.Println("Redis检查失败")
		return err
	}
	d.RedisDb = client
	log.Println("连接Redis成功")
	return nil
}
func (d *DB) initDb() error {
	var (
		mongoError error
		redisError error
	)
	if mongoError = d.mongoInit(); mongoError != nil {
		return mongoError
	} else if redisError = d.redisInit(); redisError != nil {
		return redisError
	}
	return nil
}
func getDb() *DB {
	var (
		d   *DB
		err error
	)
	d = new(DB)
	if err = d.initDb(); err != nil {
		log.Fatal("初始化数据库失败:", err)
		return nil
	} else {
		return d
	}
}

